<template lang="pug">
.view.cp-purchase-plan.fix-flex-pos
  //- 查询
  el-form.pe-search(:inline="true")
    el-form-item
      el-select(v-model="planDateType", placeholder="请选择", style="width: 108px")
        el-option(key="0", label="创建时间", :value="0")
        el-option(key="1", label="提交时间", :value="1")
        el-option(key="2", label="审批时间", :value="2")
    el-form-item
      el-date-picker(
        v-model="planDate"
        type="daterange"
        :clearable="false"
        style="width: 256px"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期")
    el-button(type="primary", @click="resetTime", plain, style="margin-right: 16px") 重置时间
    el-form-item(label="保单号 : ")
      el-input(v-model="planOrder", placeholder="申请单号", style="width: 160px")
    el-form-item(label="状态 : ")
      el-select(v-model="planStatus", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="item in statusSelectAll",
          :key="item.value",
          :label="item.name",
          :value="item.value")
    el-form-item(label="供应商 : ")
      el-select(v-model="planSupply", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="item in supplySelectAll",
          :key="item.value",
          :label="item.name",
          :value="item.value")
    el-form-item(label="申请人 : ")
      el-select(v-model="planApplicant", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="item in empSelectAll",
          :key="item.value",
          :label="item.name",
          :value="item.value")
    el-button(type="primary", @click="searchPlans") 搜索
    el-button(type="primary", @click="resetSearch", plain) 重置
    el-button(type="primary", @click="showPlanPush=true") 下推采购订单
    el-button(type="primary", @click="addPlan") 新建采购申请
    //- el-button(type="primary", @click="addOralPlan") 新建口述申请
    //- el-form-item
    //-   el-button(type="primary") 导出
  //- 列表
  .pe-table
    el-table(:data="purplans", height="100%", highlight-current-row, size="mini", @cell-dblclick="handlePlanDbClick", v-loading="loadingPlans")
      el-table-column(align="center", show-overflow-tooltip, type="index", :index="indexMethod", label="序号", :fixed="true")
      el-table-column(align="center", label="申请单号")
        template(slot-scope="scope")
          el-tooltip(
            effect="dark"
            placement="top"
            :content="scope.row.order")
            div.cell.el-tooltip(style="padding: 0") {{scope.row.order}}
      el-table-column(align="center", show-overflow-tooltip, prop="status", label="状态")
        template(slot-scope="scope")
          span {{ scope.row.status | compare-list(statusSelectAll) }}
      el-table-column(align="center", show-overflow-tooltip, prop="supply", label="供应商")
        template(slot-scope="scope")
          span {{ scope.row.supply | compare-list(supplySelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="applicant", label="申请人")
        template(slot-scope="scope")
          span {{ scope.row.applicant | compare-list(empSelectAll) }}
      el-table-column(align="center", show-overflow-tooltip, prop="depart", label="需求部门")
        template(slot-scope="scope")
          span {{ scope.row.depart | compare-list(oneDeptSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="createTime", label="创建时间")
        template(slot-scope="scope")
          span {{ scope.row.createTime | date-format }}
      el-table-column(align="center", show-overflow-tooltip, prop="submitTime", label="提交时间")
        template(slot-scope="scope")
          span {{ scope.row.submitTime | date-format }}
      el-table-column(align="center", show-overflow-tooltip, prop="approveTime", label="审批时间")
        template(slot-scope="scope")
          span {{ scope.row.approveTime | date-format }}
      el-table-column(align="center", show-overflow-tooltip, prop="comment", label="备注")
      el-table-column(align="center", label="操作", min-width="110px")
        template(slot-scope="scope")
          el-tooltip(content="查看")
            i.icon-act.el-icon-view(@click="viewPlan(scope.row)")
          el-tooltip(content="编辑")
            i.icon-act.el-icon-edit(@click="eidtPlan(scope.row, scope.$index)")
          el-tooltip(content="复制")
            i.icon-act.el-icon-hy-copy(@click="copyPlan(scope.row)")
          el-dropdown
            i.icon-act.el-icon-more
            el-dropdown-menu(slot="dropdown", class="pe-act-drop")
              el-dropdown-item.act-item(@click.native="pushPlan(scope.row)", :disabled="scope.row.status != '3'")
                i.icon-act.el-icon-download
                span 下推
              el-dropdown-item.act-item(@click.native="submitPlan(scope.row)", :disabled="scope.row.status > 0")
                i.icon-act.el-icon-hy-submit-o
                span 提交
              el-dropdown-item.act-item(@click.native="backPlan(scope.row)")
                i.icon-act.el-icon-hy-back
                span 撤回
              el-dropdown-item.act-item(@click.native="deletePlan(scope.row, scope.$index)")
                i.icon-act.el-icon-delete
                span 删除
  //- 分页
  el-pagination.pe-pagination(
    layout="total, prev, pager, next, jumper",
    @current-change="changePlanPage",
    :current-page.sync="currentPage",
    :page-size="pageSize",
    :total="purplansTotal")
  PlanView(:visible="showPlanView", :formData="formData", @close="showPlanView=false")
  PlanEdit(:visible="showPlanEdit", :formData="formData", @close="showPlanEdit=false", @save="savePlan")
  OralPlan(:visible="showOralPlan", :formData="oralData", @close="showOralPlan=false", @save="saveOralPlan")
  PlanPush(:visible="showPlanPush", @close="showPlanPush=false")
  OrderEdit(title="下推采购订单", v-if="showOrderEdit", :visible="showOrderEdit", :formData="formData", @close="showOrderEdit=false", @save="saveOrder", :pushPlan="true")
</template>

<script>
import { mapGetters } from 'vuex';
import ComApi from '@/api/common';
import PurApi from '@/api/purchase';
import PlanView from '@/components/purchase/plan/PlanView';
import PlanEdit from '@/components/purchase/plan/PlanEdit';
import PlanPush from '@/components/purchase/plan/PlanPush';
import OralPlan from '@/components/purchase/plan/OralPlan';
import OrderEdit from '@/components/purchase/order/OrderEdit';
import validate from '@/utils/validate';

const { isEmpty } = validate;

export default {
  name: 'purplan',
  components: {
    PlanView,
    PlanEdit,
    PlanPush,
    OrderEdit,
    OralPlan
  },
  data() {
    return {
      // 搜索条件
      planDateType: 0,
      planDate: [],
      planOrder: null,
      planStatus: null,
      planSupply: null,
      planApplicant: null,
      // 表格
      purplans: [],
      purplansTotal: 1,
      loadingPlans: true,
      currentPage: 1,
      pageSize: 20,
      // 组件
      formData: {
        materiels: []
      },
      oralData: {},
      showPlanPush: false,
      showPlanView: false,
      showPlanEdit: false,
      showOrderEdit: false,
      showOralPlan: false,
      statusSelectAll: []
    };
  },
  computed: {
    ...mapGetters(['empSelect', 'empSelectAll', 'oneDeptSelect', 'supplySelect', 'supplySelectAll', 'employeeId'])
  },
  methods: {
    indexMethod (i) {
      return ((this.currentPage - 1) * this.pageSize) + (i + 1);
    },
    //
    resetTime () {
      this.planDate = [];
    },
    resetSearch () {
      this.planDateType = 0;
      this.planDate = [];
      this.planOrder = null;
      this.planStatus = null;
      this.planSupply = null;
      this.planApplicant = null;
      this.$message.success('重置成功');
    },
    makeSearch () {
      const params = {};
      const dates = this.planDate.map(date => date.valueOf());
      const datePros = [
        ['startCreationTime', 'endCreationTime'],
        ['startSubmissionTime', 'endSubmissionTime'],
        ['startApprovalTime', 'endApprovalTime']
      ];

      if (dates.length) {
        params[datePros[this.planDateType][0]] = dates[0];
        params[datePros[this.planDateType][1]] = dates[1];
      }
      if (!isEmpty(this.planOrder)) {
        params.order = this.planOrder;
      }
      if (!isEmpty(this.planStatus)) {
        params.status = this.planStatus;
      }
      if (!isEmpty(this.planSupply)) {
        params.supply = this.planSupply;
      }
      if (!isEmpty(this.planApplicant)) {
        params.applicant = this.planApplicant;
      }

      return params;
    },
    searchPlans () {
      const params = this.makeSearch();
      this.loadingPlans = true;
      PurApi.getPurchasePlan(params).then((result) => {
        if (!result.status) {
          this.purplans = result.obj.records;
          this.purplansTotal = result.obj.totalNum;
        } else {
          this.purplans = [];
          this.purplansTotal = 1;
        }
        this.currentPage = 1;
        this.loadingPlans = false;
      }).catch((error) => {
        this.loadingPlans = false;
        console.log(JSON.stringify(error));
      });
    },
    // 监听Plan列表事件
    handlePlanDbClick (row, column) {
      if (column.property === 'order') {
        this.viewPlan(row);
      }
    },
    // 监听对Plan条目操作事件
    addPlan () {
      this.formData = { materiels: [] };
      this.showPlanEdit = true;
    },
    addOralPlan () {
      this.showOralPlan = true;
    },
    viewPlan (row) {
      PurApi.getPlanDetail({ id: row.order }).then((result) => {
        if (!result.status) {
          this.formData = result.obj;
          this.showPlanView = true;
        } else {
          this.$message.error(result.comment);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    eidtPlan (row, index) {
      this.focusIndex = index;
      PurApi.getPlanDetail({ id: row.order }).then((result) => {
        if (!result.status) {
          this.formData = result.obj;
          this.showPlanEdit = true;
        } else {
          this.$message.error(result.comment);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    copyPlan (row) {
      PurApi.getPlanDetail({ id: row.order }).then((result) => {
        if (!result.status) {
          this.formData = result.obj;
          this.formData.order = null;
          this.showPlanEdit = true;
        } else {
          this.$message.error(result.comment);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    pushPlan (row) {
      PurApi.getPlanDetail({ id: row.order }).then((result) => {
        if (!result.status) {
          this.formData = {
            applicant: result.obj.applicant,
            depart: result.obj.depart,
            supply: result.obj.supply,
            costCenter: result.obj.costCenter,
            reqOrder: row.order,
            materiels: result.obj.materiels,
            finances: [],
            terms: [],
            bills: []
          };
          this.showOrderEdit = true;
        } else {
          this.$message.error(result.comment);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    saveOrder (formData) {
      PurApi.saveOrder(formData).then((result) => {
        if (!result.status) {
          this.$message.success('下推成功');
          this.showOrderEdit = false;
        } else {
          this.$message.error(`下推失败：${result.comment}`);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    submitPlan (row) {
      PurApi.submitPlan({ id: row.order }).then((result) => {
        if (!result.status) {
          row.status = result.obj.status;
          row.submitTime = result.obj.submitTime;
          this.$message.success('提交成功');
        } else {
          this.$message.error(`提交失败：${result.comment}`);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    backPlan (row) {
      PurApi.backPlan({ id: row.order }).then((result) => {
        if (!result.status) {
          row.status = result.obj.status;
          row.submitTime = null;
          this.$message.success('撤回成功');
        } else {
          this.$message.error(`撤回失败：${result.comment}`);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    deletePlan (row, index) {
      this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loadingPlans = true;
        PurApi.deletePlan({ id: row.order }).then((result) => {
          if (!result.status) {
            this.purplans.splice(index, 1);
            this.purplansTotal = this.purplansTotal - 1;
            this.$message.success('删除成功');
          } else {
            this.$message.error(`删除失败：${result.comment}`);
          }
          this.loadingPlans = false;
        }).catch((error) => {
          this.loadingPlans = false;
          console.log(JSON.stringify(error));
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    savePlan (formData) {
      PurApi.savePlan(formData).then((result) => {
        if (!result.status) {
          this.$message.success('保存成功');
          // 说明为新增
          if (!formData.order) {
            this.purplans.unshift({});
            this.$set(this.purplans, 0, result.obj);
            this.purplansTotal = this.purplansTotal + 1;
          } else {
            this.$set(this.purplans, this.focusIndex, result.obj);
          }
          this.showPlanEdit = false;
        } else {
          this.$message.error(`保存失败：${result.comment}`);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    saveOralPlan (formData) {
      console.log(formData);
      this.showOralPlan = false;
    },
    // 监听计划翻页
    changePlanPage (currentPage) {
      const params = this.makeSearch();
      params.pageNum = currentPage;
      this.loadingPlans = true;
      PurApi.getPurchasePlan(params).then((result) => {
        if (!result.status) {
          this.purplans = result.obj.records;
          this.purplansTotal = result.obj.totalNum;
          this.currentPage = currentPage;
        }
        this.loadingPlans = false;
      }).catch((error) => {
        this.loadingPlans = false;
        console.log(JSON.stringify(error));
      });
    }
  },
  beforeRouteEnter (to, from, next) {
    next();
  },
  created () {
    // 状态列表
    ComApi.getStatus({ orderType: 'procurementplan' }).then((statusList) => {
      this.statusSelectAll = [{ name: '全部', value: null }].concat(statusList);
    });
    if (this.supplySelect.length) {
      this.pushPlanSupply = this.supplySelect[0].value;
    }
  },
  mounted () {
    PurApi.getPurchasePlan().then((result) => {
      if (!result.status) {
        this.purplans = result.obj.records;
        this.purplansTotal = result.obj.totalNum;
      }
      this.loadingPlans = false;
    }).catch((error) => {
      this.loadingPlans = false;
      console.log(JSON.stringify(error));
    });
  }
};
</script>

<style lang="sass">
</style>
